<template>
  <div class="map-view">
    <!-- 地图容器 -->
    <div class="map-section">
      <TencentMap
        :roomList="roomListWithLocation"
        :center="mapCenter"
        :zoom="mapZoom"
        :showMarkers="true"
        @marker-click="handleMarkerClick"
        @map-click="handleMapClick"
        @map-ready="handleMapReady"
      />
    </div>

    <!-- 房源列表侧边栏 -->
    <div class="room-sidebar" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
      <div class="sidebar-header">
        <h3>附近房源 ({{ roomListWithLocation.length }})</h3>
        <el-button 
          type="text" 
          @click="toggleSidebar"
          class="toggle-btn"
        >
          <el-icon>
            <ArrowLeft v-if="!sidebarCollapsed" />
            <ArrowRight v-if="sidebarCollapsed" />
          </el-icon>
        </el-button>
      </div>

      <div class="sidebar-content" v-if="!sidebarCollapsed">
        <!-- 搜索和筛选 -->
        <div class="sidebar-filters">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索房源"
            size="small"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select
            v-model="sortBy"
            placeholder="排序方式"
            size="small"
            @change="handleSort"
            class="sort-select"
          >
            <el-option label="距离最近" value="distance" />
            <el-option label="价格最低" value="price_asc" />
            <el-option label="价格最高" value="price_desc" />
            <el-option label="面积最大" value="area_desc" />
          </el-select>
        </div>

        <!-- 房源列表 -->
        <div class="room-list">
          <div
            v-for="room in filteredRoomList"
            :key="room.id"
            class="room-item"
            :class="{ active: selectedRoomId === room.id }"
            @click="selectRoom(room)"
          >
            <div class="room-image">
              <img 
                :src="room.image || room.housePicture || '/src/assets/imgs/blank.png'" 
                :alt="room.title || room.houseTitle"
                @error="handleImageError"
              />
            </div>
            <div class="room-info">
              <div class="room-title">{{ room.title || room.houseTitle }}</div>
              <div class="room-price">¥{{ room.price || room.rentPriceListing }}/月</div>
              <div class="room-location">
                <el-icon><Location /></el-icon>
                {{ room.address || room.location }}
              </div>
              <div class="room-distance" v-if="room.distance">
                距离您 {{ formatDistance(room.distance) }}
              </div>
            </div>
            <div class="room-actions">
              <el-button 
                type="text" 
                size="small"
                @click.stop="toggleFavorite(room)"
                :class="{ favorited: isFavorited(room.id) }"
              >
                <el-icon><Star /></el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 加载更多 -->
        <div class="load-more" v-if="hasMore">
          <el-button 
            :loading="loadingMore" 
            @click="loadMore" 
            type="primary" 
            plain
            size="small"
            class="load-more-btn"
          >
            {{ loadingMore ? '加载中...' : '加载更多' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 房源详情弹窗 -->
    <el-dialog
      v-model="showRoomDetail"
      :title="selectedRoom?.title || selectedRoom?.houseTitle"
      width="90%"
      :before-close="closeRoomDetail"
    >
      <div v-if="selectedRoom" class="room-detail">
        <div class="detail-image">
          <img 
            :src="selectedRoom.image || selectedRoom.housePicture" 
            :alt="selectedRoom.title || selectedRoom.houseTitle"
          />
        </div>
        <div class="detail-info">
          <div class="detail-price">¥{{ selectedRoom.price || selectedRoom.rentPriceListing }}/月</div>
          <div class="detail-location">
            <el-icon><Location /></el-icon>
            {{ selectedRoom.address || selectedRoom.location }}
          </div>
          <div class="detail-area" v-if="selectedRoom.area || selectedRoom.rentArea">
            面积：{{ selectedRoom.area || selectedRoom.rentArea }}㎡
          </div>
        </div>
        <div class="detail-actions">
          <el-button type="primary" @click="viewRoomDetail">查看详情</el-button>
          <el-button @click="closeRoomDetail">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, ArrowRight, Search, Location, Star } from '@element-plus/icons-vue'
import TencentMap from '@/components/TencentMap.vue'
import { getBatchRoomLocationsApi } from '@/api/location'
import { getFavorites, addFavorite, removeFavorite } from '@/api/favorite'

const props = defineProps({
  roomList: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  },
  hasMore: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['load-more', 'favorite-change'])

const router = useRouter()

// 状态管理
const roomListWithLocation = ref([])
const selectedRoomId = ref(null)
const selectedRoom = ref(null)
const showRoomDetail = ref(false)
const sidebarCollapsed = ref(false)
const searchKeyword = ref('')
const sortBy = ref('distance')
const favoriteSet = ref(new Set())
const mapCenter = ref({ lat: 39.908823, lng: 116.397470 })
const mapZoom = ref(12)
const loadingMore = ref(false)

// 计算属性
const filteredRoomList = computed(() => {
  let filtered = roomListWithLocation.value

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(room => 
      (room.title || room.houseTitle || '').toLowerCase().includes(keyword) ||
      (room.address || room.location || '').toLowerCase().includes(keyword)
    )
  }

  // 排序
  switch (sortBy.value) {
    case 'distance':
      filtered = filtered.sort((a, b) => (a.distance || 0) - (b.distance || 0))
      break
    case 'price_asc':
      filtered = filtered.sort((a, b) => (a.price || a.rentPriceListing || 0) - (b.price || b.rentPriceListing || 0))
      break
    case 'price_desc':
      filtered = filtered.sort((a, b) => (b.price || b.rentPriceListing || 0) - (a.price || a.rentPriceListing || 0))
      break
    case 'area_desc':
      filtered = filtered.sort((a, b) => (b.area || b.rentArea || 0) - (a.area || a.rentArea || 0))
      break
  }

  return filtered
})

// 生成模拟坐标数据
const generateMockCoordinates = (index, total) => {
  // 以北京为中心，生成随机坐标
  const baseLat = 39.908823
  const baseLng = 116.397470
  const radius = 0.05 // 约5公里半径
  
  const angle = (index / total) * 2 * Math.PI
  const distance = Math.random() * radius
  
  return {
    latitude: baseLat + distance * Math.cos(angle),
    longitude: baseLng + distance * Math.sin(angle)
  }
}

// 方法
const loadRoomLocations = async () => {
  if (!props.roomList.length) return

  try {
    // 尝试调用后端API
    const roomIds = props.roomList.map(room => room.id)
    const response = await getBatchRoomLocationsApi(roomIds)
    
    // 合并位置信息到房源数据
    roomListWithLocation.value = props.roomList.map(room => {
      const location = response.data.find(loc => loc.roomId === room.id)
      return {
        ...room,
        latitude: location?.latitude,
        longitude: location?.longitude,
        distance: location?.distance
      }
    })

  } catch (error) {
    console.warn('后端位置服务不可用，使用模拟数据:', error.message)
    
    // 使用模拟数据
    roomListWithLocation.value = props.roomList.map((room, index) => {
      const coords = generateMockCoordinates(index, props.roomList.length)
      return {
        ...room,
        latitude: coords.latitude,
        longitude: coords.longitude,
        distance: Math.round(Math.random() * 5000) // 0-5km随机距离
      }
    })
  }

  // 更新地图中心点
  if (roomListWithLocation.value.length > 0) {
    const firstRoom = roomListWithLocation.value[0]
    if (firstRoom.latitude && firstRoom.longitude) {
      mapCenter.value = {
        lat: firstRoom.latitude,
        lng: firstRoom.longitude
      }
    }
  }
}

const handleMarkerClick = (data) => {
  selectRoom(data.room)
}

const handleMapClick = (position) => {
  // 可以在这里实现地图点击搜索附近房源的功能
  console.log('地图点击位置:', position)
}

const handleMapReady = (map) => {
  console.log('地图加载完成')
}

const selectRoom = (room) => {
  selectedRoomId.value = room.id
  selectedRoom.value = room
  showRoomDetail.value = true
}

const closeRoomDetail = () => {
  showRoomDetail.value = false
  selectedRoom.value = null
  selectedRoomId.value = null
}

const viewRoomDetail = () => {
  if (selectedRoom.value) {
    router.push({ name: 'RentRoomDetail', params: { id: selectedRoom.value.id } })
  }
}

const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleSort = () => {
  // 排序逻辑已在计算属性中处理
}

const loadMore = () => {
  emit('load-more')
}

const toggleFavorite = async (room) => {
  try {
    const isFavorited = favoriteSet.value.has(String(room.id))
    
    if (isFavorited) {
      await removeFavorite(room.id)
      favoriteSet.value.delete(String(room.id))
      ElMessage.success('已取消收藏')
    } else {
      await addFavorite(room.id)
      favoriteSet.value.add(String(room.id))
      ElMessage.success('已收藏')
    }
    
    emit('favorite-change', { id: room.id, favorited: !isFavorited })
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

const isFavorited = (roomId) => {
  return favoriteSet.value.has(String(roomId))
}

const formatDistance = (distance) => {
  if (distance < 1000) {
    return `${Math.round(distance)}m`
  } else {
    return `${(distance / 1000).toFixed(1)}km`
  }
}

const handleImageError = (event) => {
  event.target.src = '/src/assets/imgs/blank.png'
}

const syncFavoriteSet = async () => {
  try {
    const favorites = await getFavorites()
    favoriteSet.value = new Set(favorites.map(item => String(item.id)))
  } catch (error) {
    console.error('同步收藏状态失败:', error)
  }
}

// 监听房源列表变化
watch(() => props.roomList, () => {
  loadRoomLocations()
}, { immediate: true, deep: true })

onMounted(() => {
  syncFavoriteSet()
})
</script>

<style scoped>
.map-view {
  display: flex;
  height: 100vh;
  position: relative;
}

.map-section {
  flex: 1;
  height: 100%;
}

.room-sidebar {
  width: 350px;
  background: white;
  border-left: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

.room-sidebar.sidebar-collapsed {
  width: 50px;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #f8f9fa;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.toggle-btn {
  padding: 4px;
}

.sidebar-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.sidebar-filters {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.sort-select {
  width: 100%;
}

.room-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.room-item {
  display: flex;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.room-item:hover {
  background: #f5f7fa;
  border-color: #e4e7ed;
}

.room-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.room-image {
  width: 80px;
  height: 60px;
  border-radius: 6px;
  overflow: hidden;
  margin-right: 12px;
  flex-shrink: 0;
}

.room-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.room-info {
  flex: 1;
  min-width: 0;
}

.room-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.room-price {
  font-size: 16px;
  font-weight: 700;
  color: #ff4d4f;
  margin-bottom: 4px;
}

.room-location {
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 4px;
}

.room-distance {
  font-size: 12px;
  color: #999;
}

.room-actions {
  display: flex;
  align-items: center;
  margin-left: 8px;
}

.room-actions .el-button.favorited {
  color: #ff4d4f;
}

.load-more {
  padding: 16px;
  text-align: center;
  border-top: 1px solid #e4e7ed;
}

.load-more-btn {
  width: 100%;
}

.room-detail {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-image {
  width: 100%;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
}

.detail-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.detail-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-price {
  font-size: 24px;
  font-weight: 700;
  color: #ff4d4f;
}

.detail-location {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.detail-area {
  color: #666;
}

.detail-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .map-view {
    flex-direction: column;
  }
  
  .room-sidebar {
    width: 100%;
    height: 40vh;
  }
  
  .room-sidebar.sidebar-collapsed {
    height: 50px;
  }
}
</style>
